package com.baizhi.service.impl;

import com.baizhi.entity.VoucherOrder;
import com.baizhi.service.IVoucherOrderService;
import com.baizhi.utils.IdGenerator;
import com.baizhi.utils.UserHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baizhi.dto.Result;
import com.baizhi.entity.Voucher;
import com.baizhi.mapper.VoucherMapper;
import com.baizhi.entity.SeckillVoucher;
import com.baizhi.service.ISeckillVoucherService;
import com.baizhi.service.IVoucherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gange
 * @since 2023-04-06
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private IVoucherOrderService voucherOrderService;

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        // 查询优惠券信息
        List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
        // 返回结果
        return Result.ok(vouchers);
    }

    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);
    }
    @Autowired
    private IdGenerator idGenerator;
    @Autowired
    private IVoucherOrderService VoucherOrderService;
    @Override
    public Result buyVoucher(Long voucherId) {
        //1.根据id查询voucher对象。
        Voucher byId = getById(voucherId);
        Voucher voucher = query().eq("id", voucherId).one();
        Boolean success = false;
        //2.判断voucher的类型。
        if (voucher.getType()==0){
            //普通卷
            //3.普通卷直接放入订单表中。
            Long order = voucherOrderService.createOrder(voucherId);
            return Result.ok(order);
        }else {
            //4.抢购卷
            return seckillVoucherService.seckillVoucher(voucherId);
        }
    }
}
